/*================================================================
*   Copyright (C) 2020 belonging to YangZhengQing. All rights reserved.
*   
*   文件名称：tlv_pack.c
*   创 建 者：YangZhengQing
*   创建日期：2020年03月02日
*   描    述：tlv协议，数据打包
*
*================================================================*/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tlv_pack.h"
#include "tlv_unpack.h"
#include "CRC_u8.h"
#include "type.h"

#define PACK_SIZE 200


/*
   功能：打包数据
   buff：数据缓存
   size：数据的大小
   返回：成功返回0，失败返回-1
 */


int tlv_pack(unsigned char *data, int size, unsigned char *buff)
{
	int					offset = 0;//缓存区偏移
	int					count = size;//记下数据大小
	int					i;
	unsigned char		bytes[4];//字节大小

	//crc
	CRC_8				type;//crc类型
	u8					crc;//校验和

	type.poly		= POLYNOMIAL;//多项式
	type.InitValue	= INITVAL;//初始值
	type.xor		= XOR;//异或值
	type.InputReverse = TRUE;
	type.OutputReverse= TRUE;

	memset(buff,0,sizeof(buff));

	//填充数据包
	buff[offset] = HEAD;//报头
	offset++;

	buff[offset] = TAG_SAMPLE;//数据标签
	offset++;

	//数据整型大小转化成字节
	to_bytes(bytes,size);

	//填充长度域
	buff[offset] = bytes[0];
	offset++;

	buff[offset] = bytes[1];
	offset++;

	buff[offset] = bytes[2];
	offset++;

	buff[offset] = bytes[3];
	offset++;
	
	//填充内容域
	for(i = 0; i < size; i++)
	{

		buff[offset] = data[i];
		offset++;
	}

	crc = crc8(buff, offset, type);//CRC校验
	
	//填充校验和
	buff[offset] = crc;
	offset++;

	//填充报文尾
	buff[offset] = REAR;

	//输出打包之后的数据包
	printf("打包之后的数据包: \n");
	for(i = 0; i <= offset; i++)
	{
		printf("0x%x ",buff[i]);

	}

	printf("\n");

//	printf("数据包总长度：%d\n",pack_length(buff));

	return 0;
	
}


int main(int argc, char** argv)
{
	unsigned char			data[8] = {0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88};
	unsigned char			unbuff[10];
	unsigned char			pack_buff[20];

	int						rv = 0;
	int						i;

	int						data_length = 0;

	memset(unbuff,0,sizeof(unbuff));
	memset(pack_buff,0,sizeof(pack_buff));

	tlv_pack(data,8,pack_buff);

	tlv_unpack(pack_buff,unbuff,&data_length);

	printf("数据解包结果：\n");

	for(i = 0; i < data_length; i++)
	{
		printf("0x%x ",unbuff[i]);
	}

	printf("\n");

	return 0;
}


